import pygame
import cv2
import numpy as np
import random
import sys
from tensorflow.keras.models import load_model

# 加载手势识别模型
model = load_model("models/gesture_model.h5")
# 根据错误信息设置正确尺寸
model_input_size = 64
print("模型加载成功！")


def predict_gesture(frame):
    if model is None:
        return random.choice(["布", "石头", "剪刀"])

    # 预处理图像 - 使用正确的64x64大小
    img = cv2.resize(frame, (model_input_size, model_input_size))
    img = img / 255.0
    img = np.expand_dims(img, axis=0)

    # 预测手势
    prediction = model.predict(img, verbose=0)  # 关闭详细输出
    gesture_idx = np.argmax(prediction)
    gestures = ["布", "石头", "剪刀"]
    return gestures[gesture_idx]


def get_ai_gesture(player_gesture):
    # AI必胜逻辑
    if player_gesture == "石头":
        return "布"
    elif player_gesture == "剪刀":
        return "石头"
    else:
        return "剪刀"


def determine_winner(player, ai):
    if player == ai:
        return "平局"
    if (player == "石头" and ai == "剪刀") or \
            (player == "剪刀" and ai == "布") or \
            (player == "布" and ai == "石头"):
        return "你赢了!"
    return "AI赢了!"


# 初始化Pygame
pygame.init()
W, H = 800, 600
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("AI必胜猜拳")
try:
    font = pygame.font.Font("msyh.ttf", 36)  # 指定字体文件
except:
    font = pygame.font.SysFont("microsoftyahei", 36)  # 尝试系统自带字体

# 打开摄像头
cap = cv2.VideoCapture(0)

# 游戏状态
game_state = "waiting"  # waiting, playing, result
player_gesture = ""
ai_gesture = ""
countdown = 3
last_time = pygame.time.get_ticks()

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            cap.release()
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and game_state != "playing":
                game_state = "playing"
                countdown = 3
                last_time = pygame.time.get_ticks()

    # 获取摄像头画面
    ret, frame = cap.read()
    if not ret:  # 确保有有效帧
        continue
    frame = cv2.flip(frame, 1)  # 镜像翻转

    # 用于显示的副本 - 保持合适大小
    display_frame = cv2.resize(frame.copy(), (640, 480))

    # 游戏逻辑
    current_time = pygame.time.get_ticks()
    if game_state == "playing" and current_time - last_time > 1000:
        countdown -= 1
        last_time = current_time  # 更新计时器
        if countdown <= 0:
            game_state = "result"
            try:
                player_gesture = predict_gesture(frame)
            except Exception as e:
                print(f"预测错误: {e}")
                player_gesture = random.choice(["布", "石头", "剪刀"])
            ai_gesture = get_ai_gesture(player_gesture)

    # 绘制界面
    screen.fill((40, 40, 60))

    # 显示摄像头画面
    frame_rgb = cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB)
    frame_rgb = np.rot90(frame_rgb)
    frame_surface = pygame.surfarray.make_surface(frame_rgb)
    screen.blit(frame_surface, (W // 2 - frame_surface.get_width() // 2, 100))#屏幕位置

    # 显示游戏状态
    if game_state == "waiting":
        text = font.render("按空格键开始游戏", True, (255, 255, 255))
        screen.blit(text, (W // 2 - text.get_width() // 2, 50))
    elif game_state == "playing":
        text = font.render(f"倒计时: {countdown}", True, (255, 100, 100))
        screen.blit(text, (W // 2 - text.get_width() // 2, 50))

        # 显示手势提示1
        tips = font.render("请出示手势: 石头、剪刀或布", True, (100, 200, 255))
        screen.blit(tips, (W // 2 - tips.get_width() // 2, 500))
    elif game_state == "result":
        result = determine_winner(player_gesture, ai_gesture)
        text1 = font.render(f"你出: {player_gesture}  AI出: {ai_gesture}", True, (255, 255, 0))
        text2 = font.render(result, True, (0, 255, 0) if "你赢了" in result else (255, 0, 0))
        text3 = font.render("按空格键继续", True, (200, 200, 255))

        screen.blit(text1, (W // 2 - text1.get_width() // 2, 50))
        screen.blit(text2, (W // 2 - text2.get_width() // 2, 100))
        screen.blit(text3, (W // 2 - text3.get_width() // 2, 150))

    pygame.display.flip()
    pygame.time.Clock().tick(30)